<extend name="Public:index" />
<block name="main-crumb">
 <li class="active">用户增加</li>
</block>
<block name="mycss">
<link rel="stylesheet" href="__PUBLIC__/assets/css/jquery-confirm.min.css" />
<link rel="stylesheet" type="text/css" href="__PUBLIC__/ztree/css/zTreeStyle/zTreeStyle.css" />
<style type="text/css">
	.tip{
	width:280px;padding:10px;text-align:center;background-color:#5cb85c;color:#fff;position:fixed;top:10px;left:50%;z-index:100001;margin-left:-150px;box-shadow:1px 1px 5px #333;-webkit-box-shadow:1px 1px 5px #333;
	}
	.p22{padding-left:22px !important;}
	.m5{margin-bottom:5px;}
</style>
</block>
<block name="main-content">
	<iframe name="ajaxifr" style="display:none;"></iframe>
     <div id="menuContent" class="menuContent" style="display:none; position: absolute; z-index: 1000;background-color: #fff;border: 1px #666 solid;">
    <input  style=" margin-top:5px;width:160px" type="text" onkeyup="AutoMatch(this)" placeholder="输入关键字搜索">
    <ul id="tree" class="ztree"></ul>
    </div>
    <form id="add_form"  name="add_form" action="{:U(\'department_edit\')}" method="post" class="definewidth m20">
        <table class="table table-bordered table-hover definewidth m10">
            <tr>
                    <td width="10%" class="tableleft">上级部门：</td>
                    <td>
                        <input type="hidden" id="parent_id" name="parent_id" value="{$datalist.parent_id}" />
                        <input class="form-control" id="areaSel" name="areaSel" style="width:210px" type="text" readonly onclick="showMenu(event);"  placeholder="---请选择---" required autocomplete="off"  value="{$datalist.pname}"/>
                    </td>
             </tr>
              <tr>
                <td width="10%" class="tableleft">部门名称：</td>
                <td >
                <input class="form-control" class="tableleft" style="width:210px" type="text" name="name" id="name" value="{$datalist.name}" />
                </td>
              </tr>

               <tr>
                <td width="10%" class="tableleft">部门负责人：</td>
                <td >
                   <select class="form-control" id="master_user_id" name="master_user_id" style="width: 210px;">
                            <foreach name="user_list" item="vo" >
                                <option value="{$vo.userid}" <if condition="$vo['userid'] eq $datalist['master_user_id']">selected</if> >{$vo.username}</option>
                            </foreach>
                    </select>
                </td>
              </tr>
			   <tr>
                <td width="10%" class="tableleft">选择时间表CPN：</td>
                <td>
					<a class="btn btn-default" role="button" href="{:U('addcpn')}" data-toggle="modal" data-target="#addCpnModal" data-backdrop="static"> 选择 </a>
					<!--div id="selcpnid">{$cpn_ids|str_replace="'"," ",###}</div-->
					<div class="pull-right"><button class="btn btn-primary btn-sm" type="button" onclick="clearCpn({$Think.request.id});">清空选择</button></div>
                </td>
              </tr>
			  <tr>
                <td width="10%" class="tableleft">选择时间表变量：</td>
                <td>
                  <table class="table table-bordered table-condensed table-hover">
						<tr>
						<php>
						$class_name = $varlist[0]['class_name'];
						$y = 0;
						</php>
						<volist name="varlist" id="var">
							<php>
							if($class_name != $var['class_name']){
								$class_name = $var['class_name'];
								$num = 5 - $y;
								if($num){
									$str = str_repeat("<td>&nbsp;</td>", $num);
									$y = 0;
								}
								echo $str . '</tr><tr>';
							} else{
								if($y == 5){
									$y = 0;
									echo '</tr><tr>';
								}
							}
							$y++;
							</php>

							<td><label><input class="varchk" type="checkbox" name="varid[]" value="{$var.id}" {$var['tid']==null ? '' : 'checked'} /> {$var.show_name}({$var.class_name})</label></td>
						</volist>
						</tr>
					</table>
					<div class="pull-right">
					<div class="checkbox">
						<label>
							<input class="ace ace-checkbox-2" type="checkbox" onclick="chkall(this)">
							<span class="lbl"> 全选</span>
						</label>
					</div>
                </td>
              </tr>
              <tr>
                <td class="tableleft">是否显示：</td>
                <td >
                    <input type="radio"  name = "is_show"  <if condition="$datalist['is_show'] eq 1 "> checked="checked" </if> value="1" /> 显示
                    <input type="radio"  name = "is_show" <if condition="$datalist['is_show'] eq 0 ">checked="checked" </if> value="0" /> 不显示
                </td>
              </tr>

              <tr>
                <td colspan="2" style="padding-left:20%">
                  <input type="hidden" name="id" id="id" value="{$datalist.id}" />
				  <input type="hidden" name="cpn_ids" id="cpn_ids" />
                  <input type="button"class="btn btn-primary" id="sub" name="sub" value="保存" onclick="tijiao();" />&nbsp;&nbsp;&nbsp;&nbsp;
                  <input type="reset" class="btn btn-success" value="清空" />
                </td>
              </tr>

        </table>
    </form>
	<div class="modal fade" id="addCpnModal" tabindex="-1" role="dialog" aria-labelledby="addCpn">
	   <form id="addcpnform">
			<div class="modal-dialog" role="document" style="width:60%;">
				<div class="modal-content">
				</div>
			</div>
		</form>
    </div>
</block>
<block name="myscript">
<script src="__PUBLIC__/web/js/common.js"></script>
<script type="text/javascript" src="__PUBLIC__/ztree/jquery.ztree.core.js" ></script>
<script src="__PUBLIC__/assets/js/jquery-confirm.min.js"></script>
<script language="JavaScript">
//消息通知
function notify(msg, func) {
  $( "<div>" )
	.appendTo( document.body )
	.text( msg )
	.addClass( "tip" )
	.position({
	  my: "center top",
	  at: "center top",
	  of: window
	})
	.show({
	  effect: "blind"
	})
	.delay( 1500 )
	.hide({
	  //effect: "blind",
	  duration: "slow",
	  complete: function() {
		  $( this ).remove();
		  if(typeof func != "undefined")
			func.call();
		}
	});
}

function chkall(obj){
	$('.varchk').prop('checked', obj.checked);
}

//记录选择的cpn
	var cpnid_arr = [{$cpn_ids}];
	$(function(){
		$('#addCpnModal').on('hidden.bs.modal', function(){
			$(this).removeData("bs.modal");
		});
		//对话框显示时显示选择
		$('#addCpnModal').on('shown.bs.modal', function(){
			showCheck();
		});

		//选择CPN
		//点击全选cpn按钮
		$(document).on('click', '#chkall', function(){
			$('.cpnchk').prop('checked', this.checked);
			
			$('.cpnchk').each(function(){
				if(this.checked){
					cpnid_arr.push($(this).val());
				} else {
					cpnid_arr.splice(cpnid_arr.indexOf(this.value), 1);
				}
			});
			cpnid_arr.sort();
			cpnid_arr = $.unique(cpnid_arr);
			//console.log(cpnid_arr);
			//$('#selcpnid').html(cpnid_arr.join(', '));
		});
		//点击即选择
		$(document).on('click', '.cpnchk', function(){
			if(this.checked){
				cpnid_arr.push($(this).val());
			} else {
				cpnid_arr.splice(cpnid_arr.indexOf(this.value), 1);
			}

			$('#selcpnid').html(cpnid_arr.join(', '));
			//console.log(cpnid_arr);
		});
		/*
		//点击添加cpn按钮
		$(document).on('click', '.addcpnbtn', function(){
			var cpn_ids = [];  
			$('.cpnchk:checked').each(function(){  
				cpn_ids.push($(this).val());//向数组中添加元素  
			});
			$('#cpn_ids').val(cpn_ids.join(','));
			$("#addCpnModal").modal("hide");
		});
		*/
		//点击查询按钮
		$(document).on('click', '#cpn_query', function(){
			loadcpn();
		});
	});
//显示选择对勾
function showCheck(){
	$('.cpnchk').each(function(i,el){
		if(cpnid_arr.indexOf(this.value) != -1){
			$(this).prop('checked', true);
		}
	});
}

//加载cpn条目
function loadcpn(){
	var url = "{:U('cpns')}";
	var data = $('#addcpnform').serialize();
	$.ajax({
			url: url,
			type: "POST",
			data: data,
			beforeSend: function(){
				$('#cpn_list').html('<td colspan="5" class="text-center"><i class="fa fa-spinner fa-spin"></i></td>');
			},
			complete: function(){
				$('#cpn_list').find('.fa-spin').replaceWith('加载完成！');
			},
			success: function(res){
				if(res){
					$('#cpn_list').html(res);
					showCheck();
				}
			}
	});
}

function clearCpn(department_id){
	var url= "{:U('clearCpn')}";
	if(confirm('确认清空选择的CPN吗？')){
		 $.post(url, {id: department_id}, function(res){
			if(res == '1'){
				window.location.reload();
			} else {
				notify('清空失败！');
			}
		 });
	}
}

//把选择数组逗号分隔后保存到隐藏域
function tijiao(){
	$('#cpn_ids').val(cpnid_arr.join(','));

	var id = "{$Think.get.id}";
	var url = "{:U('checkVars')}";
	var varid = [];
	$('.varchk:checked').each(function(){
		varid.push(this.value);
	});

	$.post(url,{id: id, varid: varid}, function(res){
		if(res.msg == '1'){
			$.confirm({
				title: '操作确认',
				content: res.content,
				icon: 'fa fa-question-circle',
				animation: 'scale',
				closeAnimation: 'scale',
				opacity: 0.5,
				buttons: {
					'confirm': {
						text: '确认',
						btnClass: 'btn-blue',
						action: function () {
							$('#add_form').submit();
						}
					},
					cancel: {
						text: '取消',
						action: function () {

						},
					}
				}
			});
		} else if(res.msg == '0'){
			$('#add_form').submit();
		}
	},'json');
}

function showMenu(e) {
    e = e || window.event;
    e.stopPropagation();
    var areaObj = $("#areaSel");
    //var areaOffset = $("#areaSel").offset();
    var areaOffset = $("#areaSel").position();
    $("#menuContent").css({left:areaOffset.left + "px", top:areaOffset.top + areaObj.outerHeight() + "px"}).slideDown("fast");
    $(document).on("mousedown", onBodyDown);
}

function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $(document).off("mousedown", onBodyDown);
}

function onBodyDown(event) {
    if (!(event.target.id == "areaSel" ||  event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}

//下拉树搜索框搜索
function AutoMatch(txtObj) {
    if (txtObj.value.length > 0) {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodeList = treeObj.getNodesByParamFuzzy("name", txtObj.value,null);
        //将找到的nodelist节点更新至Ztree内
        $.fn.zTree.init($("#tree"), setting, nodeList);
    } else {
        $.fn.zTree.init($("#tree"), setting, zNodes);
    }
}

var setting = {
    view: {
        selectedMulti: false
    },
    //async: {
        //enable: true,
        //url:"{:U('getNodes')}",
        //autoParam:["id", "name=n", "level=lv"],
        //otherParam:{"otherParam":"zTreeAsyncTest"},
        //dataFilter: filter
    //},
    data: {
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: ""
        }
    },
    callback: {
        onClick: onClick,
        //onDblClick: onDblClick
    }
};

function onClick(e, treeId, treeNode) {
    /*var pNode = treeNode.getParentNode();
    var ppNode = pNode.getParentNode();

    $('#areaid').val(ppNode.id);
    $('#areaname').val(ppNode.name);

    $('#substationid').val(pNode.id);
    $('#substationname').val(pNode.name);*/

    $('#parent_id').val(treeNode.id);
    $('#areaSel').val(treeNode.name);
    hideMenu();
}

var getData = function() {
    $.get('{:U(\'getDepartment\')}', function(nodes){
        zNodes = nodes;
        $.fn.zTree.init($("#tree"), setting, nodes);
    }, 'json');
}

$(function(){
    getData();
});
</script>
</block>